import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:hinge/common/index.dart';
import 'package:uuid/uuid.dart';
import 'package:intl/intl.dart';
import 'package:go_router/go_router.dart';
import 'dart:async';
import 'dart:convert';

class AIChatPage extends StatefulWidget {
  final String initialMessage;

  const AIChatPage({Key? key, required this.initialMessage}) : super(key: key);

  @override
  _AIChatPageState createState() => _AIChatPageState();
}

class _AIChatPageState extends State<AIChatPage>
    with SingleTickerProviderStateMixin {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final AIChatService _chatService = AIChatService();
  final FocusNode _focusNode = FocusNode();
  final List<ChatMessage> _messages = [];
  String? _conversationId;
  final String _sessionId =
      '${DateFormat('yyyyMMdd').format(DateTime.now())}_${const Uuid().v4()}';
  bool _isLoading = false;
  UserModel? _currentUser;
  late AnimationController _animationController;

  // 用于取消流式响应的订阅
  StreamSubscription? _streamSubscription;

  // 添加加载动画计时器
  Timer? _loadingAnimationTimer;
  // 加载动画文本
  String _loadingText = '';
  // 加载动画计数
  int _loadingCount = 0;

  static const String _spChatMessagesKey = 'ai_chat_messages';
  static const String _spConversationIdKey = 'ai_chat_conversation_id';

  @override
  void initState() {
    super.initState();
    _loadUserData();
    _loadChatHistory();

    // 初始化动画控制器，延长动画持续时间到800毫秒
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );

    // 添加Hero动画结束后自动聚焦的监听
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.delayed(const Duration(milliseconds: 900), () {
        if (_currentUser != null && !UserService.isGuestUser()) {
          // 如果用户已登录，自动聚焦输入框
          _focusNode.requestFocus();
        }
      });
    });
  }

  void _loadUserData() {
    _currentUser = UserService.getCurrentUser();

    // 如果用户已登录并且有初始消息，则填充到输入框
    if (_currentUser != null && !UserService.isGuestUser()) {
      if (widget.initialMessage.isNotEmpty) {
        // 填充到输入框而不是立即发送
        _messageController.text = widget.initialMessage;
      }
    } else if (widget.initialMessage.isNotEmpty) {
      // 如果用户未登录，显示登录对话框
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _showLoginRequiredDialog("search AI assistant");
      });
    }
  }

  // Login required dialog
  void _showLoginRequiredDialog(String actionName) {
    CustomDialog.show(
      context: context,
      title: 'Login Required',
      content:
          'You need to log in to $actionName. Would you like to log in now?',
      cancelText: 'Cancel',
      confirmText: 'Login',
      onConfirm: () {
        // Navigate to login page with return path parameter
        context.push('/login?returnTo=/ai_chat', extra: widget.initialMessage);
      },
    );
  }

  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  // 启动加载动画
  void _startLoadingAnimation() {
    // 取消已有的计时器
    _loadingAnimationTimer?.cancel();
    // 重置加载文本和计数
    _loadingCount = 0;
    _loadingText = '...'; // 初始设置为三个点

    // 创建新的计时器，每300毫秒更新一次
    _loadingAnimationTimer = Timer.periodic(const Duration(milliseconds: 300), (
      timer,
    ) {
      setState(() {
        _loadingCount = (_loadingCount + 1) % 4;
        // 使用不同的可见点数，但保持总长度不变
        if (_loadingCount == 0) {
          _loadingText = '   '; // 三个空格
        } else {
          _loadingText =
              '${'.'.padRight(_loadingCount, '.')}${' '.padRight(3 - _loadingCount, ' ')}';
        }
      });
    });
  }

  // 停止加载动画
  void _stopLoadingAnimation() {
    _loadingAnimationTimer?.cancel();
    _loadingAnimationTimer = null;
    _loadingText = '';
  }

  // 加载聊天历史
  Future<void> _loadChatHistory() async {
    if (_currentUser == null || UserService.isGuestUser()) return;

    try {
      final String? messagesJson = await SpUtil.getString(_spChatMessagesKey);
      final String? savedConversationId = await SpUtil.getString(
        _spConversationIdKey,
      );

      if (messagesJson != null && messagesJson.isNotEmpty) {
        final List<dynamic> messagesList = json.decode(messagesJson);
        setState(() {
          _messages.clear();
          _messages.addAll(
            messagesList.map((msg) => ChatMessage.fromJson(msg)).toList(),
          );
          _conversationId = savedConversationId;
        });
      }
    } catch (e) {
      debugPrint('加载聊天历史失败: $e');
    }
  }

  // 保存聊天历史
  Future<void> _saveChatHistory() async {
    if (_currentUser == null || UserService.isGuestUser()) return;

    try {
      final List<Map<String, dynamic>> messagesJson =
          _messages.map((msg) => msg.toJson()).toList();

      await SpUtil.setString(_spChatMessagesKey, json.encode(messagesJson));
      if (_conversationId != null) {
        await SpUtil.setString(_spConversationIdKey, _conversationId!);
      }
    } catch (e) {
      debugPrint('保存聊天历史失败: $e');
    }
  }

  Future<void> _sendMessage(String content) async {
    if (content.isEmpty) return;

    // Check if user is logged in
    if (_currentUser == null || UserService.isGuestUser()) {
      _showLoginRequiredDialog("chat with AI assistant");
      return;
    }

    // 取消之前的流式响应（如果有）
    _streamSubscription?.cancel();
    _stopLoadingAnimation();

    setState(() {
      _messages.add(
        ChatMessage(content: content, isUser: true, timestamp: DateTime.now()),
      );
      _isLoading = true;
    });

    // 保存消息历史
    await _saveChatHistory();

    _scrollToBottom();

    try {
      final aiMessage = ChatMessage(
        content: ' ',
        isUser: false,
        timestamp: DateTime.now(),
        isLoading: true,
      );

      setState(() {
        _messages.add(aiMessage);
      });

      _scrollToBottom();

      _startLoadingAnimation();

      _streamSubscription = _chatService
          .sendMessageStream(
            bundleId: 'com.hinge.ios',
            sessionId: _sessionId,
            content: content,
            conversationId: _conversationId,
          )
          .listen(
            (streamedContent) {
              if (streamedContent.isNotEmpty) {
                _stopLoadingAnimation();
              }

              setState(() {
                final lastAiMessageIndex = _messages.lastIndexWhere(
                  (msg) => !msg.isUser,
                );
                if (lastAiMessageIndex != -1) {
                  _messages[lastAiMessageIndex] = ChatMessage(
                    content: streamedContent,
                    isUser: false,
                    timestamp: _messages[lastAiMessageIndex].timestamp,
                    isLoading: false,
                  );
                }
              });

              // 保存更新后的消息历史
              _saveChatHistory();

              _scrollToBottom();
            },
            onDone: () {
              _stopLoadingAnimation();
              setState(() {
                _isLoading = false;
                _conversationId = _chatService.latestConversationId;
              });
              // 保存最终的对话ID
              _saveChatHistory();
            },
            onError: (error) {
              _stopLoadingAnimation();
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text('发送消息失败: $error')));
              setState(() {
                _isLoading = false;
              });
            },
          );
    } catch (e) {
      _stopLoadingAnimation();
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Failed to send message: $e')));
      setState(() {
        _isLoading = false;
      });
    }

    _messageController.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFC4B4FD), Color(0xFFEFE0FF)],
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              SizedBox(height: 10.h),
              Row(
                children: [
                  SizedBox(width: 20.w),
                  GestureDetector(
                    onTap: () {
                      // Use explicit GoRouter method
                      final router = GoRouter.of(context);
                      if (router.canPop()) {
                        router.pop();
                      } else {
                        // If can't go back, navigate to home
                        router.go('/');
                      }
                    },
                    child: Icon(IconFont.back, color: Colors.white, size: 28.w),
                  ),
                  SizedBox(width: 10.w),
                  Text(
                    'AI Assistant',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20.sp,
                      fontFamily: 'Inter',
                    ),
                  ),
                  const Spacer(),
                  SizedBox(width: 20.w),
                ],
              ),
              SizedBox(height: 28.h),

              // Message list
              Expanded(
                child:
                    _messages.isEmpty
                        ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.assistant_outlined,
                                color: Colors.white.withOpacity(0.7),
                                size: 64.w,
                              ),
                              SizedBox(height: 16.h),
                              Text(
                                'Ask me anything about perfumes!',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18.sp,
                                  fontFamily: 'Inter',
                                ),
                              ),
                            ],
                          ),
                        )
                        : ListView.builder(
                          controller: _scrollController,
                          padding: EdgeInsets.symmetric(horizontal: 24.w),
                          itemCount: _messages.length,
                          itemBuilder: (context, index) {
                            final message = _messages[index];
                            return Container(
                              margin: EdgeInsets.only(bottom: 20.h),
                              child: Row(
                                mainAxisAlignment:
                                    message.isUser
                                        ? MainAxisAlignment.end
                                        : MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children:
                                    message.isUser
                                        ? [
                                          // Right side: content, avatar
                                          Flexible(
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.end,
                                              children: [
                                                _currentUser != null &&
                                                        _currentUser!
                                                            .avatar
                                                            .isNotEmpty
                                                    ? CircleAvatar(
                                                      radius: 24.w,
                                                      backgroundImage:
                                                          AssetImage(
                                                            _currentUser!
                                                                .avatar,
                                                          ),
                                                    )
                                                    : CircleAvatar(
                                                      radius: 24.w,
                                                      backgroundColor:
                                                          Colors.white,
                                                      child: Icon(
                                                        Icons.person,
                                                        color: const Color(
                                                          0xFFA794FD,
                                                        ),
                                                        size: 24.w,
                                                      ),
                                                    ),
                                                SizedBox(height: 8.h),
                                                _buildMessageBubble(message),
                                              ],
                                            ),
                                          ),
                                        ]
                                        : [
                                          // Left side: avatar, content
                                          Flexible(
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                CircleAvatar(
                                                  radius: 24.w,
                                                  backgroundColor: Colors.white,
                                                  child: Icon(
                                                    Icons.assistant,
                                                    color: const Color(
                                                      0xFFA794FD,
                                                    ),
                                                    size: 24.w,
                                                  ),
                                                ),
                                                SizedBox(height: 8.h),
                                                _buildMessageBubble(message),
                                              ],
                                            ),
                                          ),
                                        ],
                              ),
                            );
                          },
                        ),
              ),

              // Bottom input field
              Container(
                padding: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 30.h),
                color: Colors.transparent,
                child: Hero(
                  tag: 'search_input',
                  // 添加Hero动画持续时间设置
                  transitionOnUserGestures: true,
                  createRectTween: (begin, end) {
                    return MaterialRectCenterArcTween(begin: begin, end: end);
                  },
                  flightShuttleBuilder: (
                    flightContext,
                    animation,
                    flightDirection,
                    fromHeroContext,
                    toHeroContext,
                  ) {
                    // 自定义Hero过渡效果
                    return Material(
                      color: Colors.transparent,
                      child: Container(
                        decoration: BoxDecoration(
                          color: Color.lerp(
                            const Color(0xFFA393E3),
                            Colors.black.withOpacity(0.3),
                            animation.value,
                          ),
                          borderRadius: BorderRadius.circular(24.w),
                          border: Border.all(
                            color: Colors.white,
                            width: 2 - animation.value,
                          ),
                        ),
                        child: Center(
                          child: Text(
                            widget.initialMessage.isNotEmpty
                                ? widget.initialMessage
                                : 'Ask a question...',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontFamily: 'Inter',
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ),
                    );
                  },
                  child: Stack(
                    alignment: Alignment.centerRight,
                    children: [
                      Container(
                        padding: EdgeInsets.only(right: 44.w),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.3),
                          borderRadius: BorderRadius.circular(24.w),
                        ),
                        child: TextField(
                          controller: _messageController,
                          focusNode: _focusNode,
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: 'Ask a question...',
                            hintStyle: TextStyle(
                              fontSize: 15.sp,
                              color: Colors.white,
                              fontFamily: 'Inter',
                            ),
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                              vertical: 12.h,
                            ),
                          ),
                          style: TextStyle(
                            fontSize: 15.sp,
                            color: Colors.white,
                            fontFamily: 'Inter',
                          ),
                          onSubmitted: _sendMessage,
                        ),
                      ),
                      Positioned(
                        right: 16.w,
                        child: GestureDetector(
                          onTap: () {
                            if (_messageController.text.trim().isNotEmpty) {
                              _sendMessage(_messageController.text);
                            }
                          },
                          child: Icon(
                            IconFont.send,
                            color: Colors.white,
                            size: 22.w,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMessageBubble(ChatMessage message) {
    // 如果消息正在加载中，显示加载动画
    if (message.isLoading == true) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
        decoration: BoxDecoration(
          color: Color(0xFFBD88FF),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(0.w),
            topRight: Radius.circular(20.w),
            bottomLeft: Radius.circular(20.w),
            bottomRight: Radius.circular(20.w),
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 使用固定宽度的文本，防止宽度变化
            SizedBox(
              width: 30.w, // 设置固定宽度
              child: Text(
                _loadingText,
                style: TextStyle(
                  fontSize: 18.sp,
                  height: 1.5,
                  color: Colors.white,
                  fontFamily: 'Inter',
                ),
              ),
            ),
          ],
        ),
      );
    }

    // 正常消息气泡
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
      decoration: BoxDecoration(
        color: message.isUser ? Color(0xFFDBBFFF) : Color(0xFFBD88FF),
        borderRadius:
            message.isUser
                ? BorderRadius.only(
                  topRight: Radius.circular(0.w),
                  topLeft: Radius.circular(20.w),
                  bottomLeft: Radius.circular(20.w),
                  bottomRight: Radius.circular(20.w),
                )
                : BorderRadius.only(
                  topLeft: Radius.circular(0.w),
                  topRight: Radius.circular(20.w),
                  bottomLeft: Radius.circular(20.w),
                  bottomRight: Radius.circular(20.w),
                ),
      ),
      child: Text(
        message.content,
        style: TextStyle(
          fontSize: 14.sp,
          height: 2,
          color: Colors.white,
          fontFamily: 'Inter',
        ),
      ),
    );
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    _focusNode.dispose();
    _animationController.dispose();
    _streamSubscription?.cancel(); // 取消流订阅
    _loadingAnimationTimer?.cancel(); // 取消加载动画计时器
    super.dispose();
  }
}

class ChatMessage {
  final String content;
  final bool isUser;
  final DateTime timestamp;
  final bool isLoading;

  ChatMessage({
    required this.content,
    required this.isUser,
    required this.timestamp,
    this.isLoading = false,
  });

  // 从JSON解析
  factory ChatMessage.fromJson(Map<String, dynamic> json) {
    return ChatMessage(
      content: json['content'] as String,
      isUser: json['isUser'] as bool,
      timestamp: DateTime.parse(json['timestamp'] as String),
      isLoading: false, // 从存储加载时永远不会是加载状态
    );
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'content': content,
      'isUser': isUser,
      'timestamp': timestamp.toIso8601String(),
      // 不保存isLoading状态，因为加载时总是false
    };
  }
}
